package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func main() {

	// 打开文件
	file, err := os.Open("d:/_tmp/kafka.txt")

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return
	}

	defer file.Close()

	// 创建reader
	// defaultBufSize = 4096
	reader := bufio.NewReader(file)

	// 读取文件内容
	for {

		line, err := reader.ReadString('\n')

		if err == io.EOF {
			break
		}

		fmt.Print(line)
	}

	fmt.Println("---")

	// ioutil
	bytes, err := ioutil.ReadFile("d:/_tmp/kafka.txt")

	if err != nil {
		fmt.Printf("Read file error: %v\n", err)
		return
	}

	// 转为字符串
	fmt.Println(string(bytes))

	fmt.Println("---")

	// 字符统计
	counter, err := charCount("D:/tmp/test.txt")
	fmt.Println(counter, err)
}

func PathExists(filename string) (bool, error) {

	_, err := os.Stat(filename)

	if err == nil {
		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}

	return false, err
}

type charCounter struct {
	chCount    int
	numCount   int
	spaceCount int
	otherCount int
}

func charCount(filename string) (charCounter, error) {

	counter := charCounter{}

	// 打开文件
	file, err := os.Open(filename)

	if err != nil {
		fmt.Printf("Open file error: %v\n", err)
		return counter, err
	}

	defer file.Close()

	// 创建reader
	reader := bufio.NewReader(file)

	// 读取文件内容
	for {

		line, err := reader.ReadString('\n')

		runes := []rune(line)

		for _, v := range runes {

			switch {
			case v >= 'a' && v <= 'z':
				fallthrough
			case v >= 'A' && v <= 'Z':
				counter.chCount++
			case v >= '0' && v <= '9':
				counter.numCount++
			case v == ' ' || v == '\t':
				counter.spaceCount++
			default:
				counter.otherCount++
			}
		}

		if err == io.EOF {
			break
		}
	}

	return counter, nil
}
